package dev

import (
	"encoding/json"
	"fmt"
	"gorm.io/gorm"
	"log"
	"net"
	"os"
	"os/exec"
)

func GenerateConfigForUser(user UserConfig, db *gorm.DB) error {
	// 检测端口是否被占用
	if isPortInUse(user.ServerPort) {
		log.Println("端口：%d正在被占用", user.ServerPort)
		return fmt.Errorf("端口 %d 正在被占用", user.ServerPort)
	}

	if user.Password == "" {
		return fmt.Errorf("password 不能为空")
	}
	var maxPort int
	if err := db.Model(&UserConfig{}).Select("MAX(server_port)").Scan(&maxPort).Error; err != nil {
		//return fmt.Errorf("查询失败")
		maxPort = 8388
	}
	config := map[string]interface{}{
		"server":      "0.0.0.0",
		"server_port": maxPort + 1,
		"password":    user.Password,
		"method":      "aes-128-gcm",
		"timeout":     300,
		"fast_open":   false,
		"mode":        "tcp_and_udp",
	}

	filePath := fmt.Sprintf("/etc/shadowsocks-libev/config_%s.json", user.Username)
	file, err := os.Create(filePath)
	if err != nil {
		return fmt.Errorf("failed to create config file: %v", err)
	}
	defer file.Close()

	// 启动 Shadowsocks 服务器
	cmd := exec.Command("nohup", "ss-server", "-c", filePath, ">", "/var/log/shadowsocks.log", "2>&1", "&")
	err = cmd.Start()
	if err != nil {
		return fmt.Errorf("failed to start Shadowsocks server: %v", err)
	}

	encoder := json.NewEncoder(file)
	encoder.SetIndent("", "  ")
	if err := encoder.Encode(config); err != nil {
		return fmt.Errorf("failed to write config file: %v", err)
	}

	log.Println("Shadowsocks configuration updated for user:", user.Username)
	return nil
}

// isPortInUse 检测指定的端口是否被占用
func isPortInUse(port int) bool {
	address := fmt.Sprintf(":%d", port)
	ln, err := net.Listen("tcp", address)
	if err != nil {
		return true // 端口被占用
	}
	_ = ln.Close() // 关闭监听器
	return false   // 端口未被占用
}

func RestartShadowsocks() {
	cmd := exec.Command("systemctl", "restart", "shadowsocks-libev")
	if err := cmd.Run(); err != nil {
		log.Fatalf("failed to restart Shadowsocks: %v", err)
	}
	log.Println("Shadowsocks service restarted")
}
